#include "physics/triangle_mesh.hpp"

#include "modes/world.hpp"

TriangleMesh::~TriangleMesh()
{
	if (m_body)
	{
		RaceManager::getWorld()->getPhysics()->removeBody(m_body);
		delete m_body;
		delete m_motion_state;
		delete m_collision_shape;
	}
}

void TriangleMesh::addTriangle(const btVector3& t1, const btVector3& t2, 
							   const btVector3& t3, const Material* m)
{
	m_triangleIndex2Material.push_back(m);
	m_mesh.addTriangle(t1, t2, t3);
}

void TriangleMesh::createBody(btCollisionObject::CollisionFlags flags)
{
	if (m_triangleIndex2Material.size() == 0)
	{
		m_collision_shape = NULL;
		m_motion_state = NULL;
		m_body = NULL;
		return;
	}

	m_collision_shape = new btBvhTriangleMeshShape(&m_mesh, true);
	btTransform startTransform;
	startTransform.setIdentity();
	m_motion_state = new btDefaultMotionState(startTransform);
	btRigidBody::btRigidBodyConstructionInfo info(0.0f, m_motion_state, m_collision_shape);
	m_body = new btRigidBody(info);

	RaceManager::getWorld()->getPhysics()->addBody(m_body);
	m_user_pointer.set(this);
	m_body->setUserPointer(&m_user_pointer);
	m_body->setCollisionFlags(m_body->getCollisionFlags() |
							flags |
							btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
}

void TriangleMesh::removeBody()
{
	RaceManager::getWorld()->getPhysics()->removeBody(m_body);
	delete m_body;
	m_body = 0;
}


